package com.liyunc.demo.comp.auth;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

/**
 * @author liyuncong
 * @version 1.0
 * @file AuthenticatedUser.java
 * @brief 已经认证过的用户
 * @details 已经认证过的用户
 * @date 2022-03-15
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2022-03-15               liyuncong        Created
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AuthenticatedUser<T> {
    private String loginUsername;
    private String username;
    private String userId;
    private T properties;

    /**
     * 构造函数.
     *
     * @param loginUsername 登录名
     * @param username      用户名
     * @param userId        用户id
     */
    public AuthenticatedUser(String loginUsername, String username, String userId) {
        this.loginUsername = loginUsername;
        this.username = username;
        this.userId = userId;
    }

    /**
     * 获取当前用户.
     *
     * @return 用户信息
     */
    public static Optional<AuthenticatedUser<?>> currentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return Optional.ofNullable(
            authentication instanceof AuthenticatedAccount
                ? ((AuthenticatedAccount<?>) authentication).getUser() : null);
    }
}
